import base_routers from "../../base_routers";

export default async (ctx, next) => {

    const md5 = base_routers.forge.md.md5.create();

    const video = base_routers.model.video.findOne({
        where: {id: ctx.request.body.videoId}
    });

    const payment_history = base_routers.model.payment_history.findOne({
        where: {
            type: ctx.request.body.type,
            serviceProvider: "ispay",
            userId: ctx.state.user.id,
            videoId: ctx.request.body.videoId,
            [base_routers.Op.or]: [
                {
                    status: '0'
                },
                {
                    status: '1'
                }
            ],
            createdAt: {
                [base_routers.Op.gte]: new Date().getTime() - base_routers.config.payment_history.expiresIn,
                [base_routers.Op.lte]: new Date()
            }
        }
    });

    const result = Promise.all([video, payment_history])
        .then(async ([_video, _payment_history]) => {
            if (!_video) {
                throw new base_routers.exception(30000)
            }

            if (!_video.dataValues.current_price) {
                throw new base_routers.exception(30001)
            }

            if (_payment_history && _payment_history.dataValues.status === "1") {
                throw new base_routers.exception(40003)
            }

            if (_payment_history) {
                // 记录存在,读取记录返回客户端
                _payment_history = _payment_history.dataValues;
                _payment_history = {
                    Money: _payment_history.price * 100,
                    Notify_url: `https://www.baidu.com/`,//`${ctx.origin}/payment/ispay/notify`
                    Return_url: _payment_history.returnURL,
                    Subject: _payment_history.subject,
                    attachData: _payment_history.metaData,
                    orderNumber: _payment_history.orderNumber,
                    payChannel: _payment_history.channel,
                    payId: base_routers.config.payment.ispay.payId,
                    Sign: _payment_history.token
                }
            }

            return [_video, _payment_history]
        })
        .then(async ([_video, _payment_history]) => {

            if (_payment_history) {
                return [null, _payment_history]
            }

            const _Date = new Date();
            let getMonth = (_Date.getMonth() + 1).toString();
            const getFullYear = _Date.getFullYear().toString();
            const getDate = _Date.getDate().toString();
            const random = (Math.random() * 10000000000000000000) | 0;

            const ispayRequestData = {
                Money: _video.dataValues.current_price * 100,
                Notify_url: `https://www.baidu.com/`,//`${ctx.origin}/payment/ispay/notify`
                Return_url: ctx.request.body.Return_url,
                Subject: _video.dataValues.title,
                attachData: ctx.request.body.attachData,
                orderNumber: `${getFullYear + (getMonth.length === 1 ? getMonth = '0' + getMonth : getMonth) + getDate}${random}${_Date.getTime()}`.replace(/\-/g, ""),
                payChannel: ctx.request.body.payChannel,
                payId: base_routers.config.payment.ispay.payId,
                Sign: ""
            };


            let Sign = Object.values(ispayRequestData).join("") + base_routers.config.payment.ispay.payKey;
            Sign = md5.update(Sign, "utf8").digest().toHex();

            ispayRequestData.Sign = Sign;

            return [ispayRequestData, _payment_history]

        })
        .then(async ([ispayRequestData, _payment_history]) => {

            if (_payment_history) {
                return _payment_history
            }

            const data = {
                orderNumber: ispayRequestData.orderNumber,
                type: ctx.request.body.type,
                serviceProvider: "ispay",
                channel: ctx.request.body.payChannel,
                subject: ispayRequestData.Subject,
                metaData: ispayRequestData.attachData,
                returnURL: ispayRequestData.Return_url,
                price: ispayRequestData.Money / 100,
                userId: ctx.state.user.id,
                videoId: ctx.request.body.videoId,
                token: ispayRequestData.Sign
            };


            base_routers.model.payment_history.create(data);

            return ispayRequestData
        });


    ctx.clientData = result;

    await next();
}